import React, { Suspense } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import PageLoading from '@/components/PageLoading';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Form, Input, Tabs, Tree, Modal, Radio, Checkbox, Button, message, Card } from 'antd';
import { connect } from 'dva';
import styles from "./index.less";
import UserSession from '@/UserSession';

const { TreeNode } = Tree;
const { TabPane } = Tabs;

class AuthAddModal extends React.Component {

  state = {
    roleName: '',
    description: '',
    authId: null,

    menuTree: {
      artificialMenu: [],
      knowledgeMenu: [],
      llmMenu: [],
      modelMenu: [],
      robotMenu: [],
      securityMenu: [],
      staffMenu: [],
      workOrderMenu:[]
    },
    checkedKeys: {
      artificialKeys: [],
      knowledgeKeys: [],
      llmKeys: [],
      modelKeys: [],
      robotKeys: [],
      securityKeys: [],
      staffKeys: [],
      workOrderKeys:[]
    },
    expandedKeys: {
      artificialKeys: [],
      knowledgeKeys: [],
      llmKeys: [],
      modelKeys: [],
      robotKeys: [],
      securityKeys: [],
      staffKeys: [],
      workOrderKeys:[]
    },
  }

  componentDidMount() {
    this.initData()
  }

  initData = () => {
    const { location: { query } } = this.props;
    if (query && query?.authId) {
      this.getMenusByRoleId(query.authId)
    } else {
      this.getMenusByTenantId();
    };
    this.setState({ authId: query?.authId ? query.authId : null })
  }

  getMenusByTenantId = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'authManage/getMenuTreeByTenantId',
      payload: { id: currentUser.tenantId },
      callback: res => {
        // this.setState({ menuTree: res ? res : [] }, () => {
        //   let arr = res ? res : [];
        //   this.setMenuChecked(arr);
        // })
        this.getExpandedMenu(res);
        this.setState({ menuTree: res ? res : [] }, () => {
          this.getSelectMenu(res ? res.artificialMenu : [], "artificialKeys");
          this.getSelectMenu(res ? res.knowledgeMenu : [], "knowledgeKeys");
          this.getSelectMenu(res ? res.llmMenu : [], "llmKeys");
          this.getSelectMenu(res ? res.modelMenu : [], "modelKeys");
          this.getSelectMenu(res ? res.robotMenu : [], "robotKeys");
          this.getSelectMenu(res ? res.securityMenu : [], "securityKeys");
          this.getSelectMenu(res ? res.staffMenu : [], "staffKeys");
          this.getSelectMenu(res ? res.workOrderMenu : [], "workOrderKeys");
        });
      },
    });
  }

  getSelectMenu = (data, type) => {
    const that = this;
    let { checkedKeys } = that.state;
    if(data && data.length > 0) {
      data.map(item => {
        if (item.children && item.children.length > 0) {
          const childrenChecked = item.children.filter(child => child.checked);
          if (childrenChecked.length === item.children.length) {
            checkedKeys[type].push(item.id);
          };
          that.getSelectMenu(item.children, type);
        } else {
          if (item.checked) {
            checkedKeys[type].push(item.id);
          };
        }
      });
    };
    that.setState({ checkedKeys });
  }

  getExpandedMenu = res => {
    let { expandedKeys } = this.state;
    let treeData = (data, type) => {
      if (data && data.length > 0) {
        data.map(item => {
          if (item.children && item.children.length > 0) {
            expandedKeys[type].push(item.id);
            treeData(item.children, type);
          }
        })
      }
    };
    treeData(res ? res.artificialMenu : [], "artificialKeys");
    treeData(res ? res.knowledgeMenu : [], "knowledgeKeys");
    treeData(res ? res.llmMenu : [], "llmKeys");
    treeData(res ? res.modelMenu : [], "modelKeys");
    treeData(res ? res.robotMenu : [], "robotKeys");
    treeData(res ? res.securityMenu : [], "securityKeys");
    treeData(res ? res.staffMenu : [], "staffKeys");
    treeData(res ? res.workOrderMenu : [], "workOrderKeys");
    console.log(expandedKeys);
    console.log(expandedKeys.knowledgeKeys);
    this.setState({ expandedKeys });
  }

  getMenusByRoleId = authId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'authManage/getMenuTreeByRoleId',
      payload: { id: authId },
      callback: res => {
        console.log(res);
        this.setState({
          menuTree: res.menuTree ? res.menuTree : [],
          roleName: res.roleName,
          description: res.description,
        }, () => {
          // let arr = res.tree ? res.tree : [];
          // this.getSelectMenu(arr);
          this.getExpandedMenu(res.menuTree ? res.menuTree : []);
          this.getSelectMenu(res ? res.menuTree.artificialMenu : [], "artificialKeys");
          this.getSelectMenu(res ? res.menuTree.knowledgeMenu : [], "knowledgeKeys");
          this.getSelectMenu(res ? res.menuTree.llmMenu : [], "llmKeys");
          this.getSelectMenu(res ? res.menuTree.modelMenu : [], "modelKeys");
          this.getSelectMenu(res ? res.menuTree.robotMenu : [], "robotKeys");
          this.getSelectMenu(res ? res.menuTree.securityMenu : [], "securityKeys");
          this.getSelectMenu(res ? res.menuTree.staffMenu : [], "staffKeys");
          this.getSelectMenu(res ? res.menuTree.workOrderMenu : [], "workOrderKeys");
        })
      },
    });
  }


  changeRoleName = e => {
    this.setState({ roleName: e.target.value })
  }

  // changeDescription = e => {
  //   this.setState({ description: e.target.value })
  // }

  onCheck = (keys, type) => {
    let { checkedKeys } = this.state;
    checkedKeys[type] = keys;
    this.setState({ checkedKeys });
  };

  onExpand = (keys, type) => {
    let { expandedKeys } = this.state;
    expandedKeys[type] = keys;
    this.setState({ expandedKeys });
  }

  onClose = () => {
    this.setState({
      roleName: '',
      description: '',
      authId: null,

      menuTree: {
        artificialMenu: [],
        knowledgeMenu: [],
        llmMenu: [],
        modelMenu: [],
        robotMenu: [],
        securityMenu: [],
        staffMenu: [],
        workOrderMenu: [],
      },
      checkedKeys: {
        artificialKeys: [],
        knowledgeKeys: [],
        llmKeys: [],
        modelKeys: [],
        robotKeys: [],
        securityKeys: [],
        staffKeys: [],
        workOrderKeys:[]
      },
      expandedKeys: {
        artificialKeys: [],
        knowledgeKeys: [],
        llmKeys: [],
        modelKeys: [],
        robotKeys: [],
        securityKeys: [],
        staffKeys: [],
        workOrderKeys:[]
      },
    }, () => {
      const { history } = this.props;
      const currentUser = UserSession.getCurrentUser()
      history.push({ pathname:currentUser.tenantId == '1' ? '/defaultData/authManage' : "/authManage", });
    })
  }

  onSubmit = () => {
    const { authId } = this.state;
    const { roleName, description, checkedKeys } = this.state;
    if (roleName === '') {
      return message.error(formatMessage({ id: 'authAddModal.fillRoleName', defaultMessage: '请填写角色名称' }))
    };
    // if (description === '') {
    //   return message.error('请填写角色说明')
    // };
    if (!checkedKeys && checkedKeys.artificialKeys.length === 0 &&
      checkedKeys.knowledgeKeys.length === 0 && checkedKeys.llmKeys.length === 0 &&
      checkedKeys.modelKeys.length === 0 && checkedKeys.robotKeys.length === 0 &&
      checkedKeys.securityKeys.length === 0 && checkedKeys.staffKeys.length === 0 && checkedKeys.workOrderKeys.length === 0
    ) {
      return message.error(formatMessage({ id: 'authAddModal.selectFunctionPermission', defaultMessage: '请选择功能权限' }))
    };
    if (authId) {
      this.editRole();
    } else {
      this.addRole()
    }
  }

  addRole = () => {
    const { roleName, description, checkedKeys } = this.state;
    const { dispatch } = this.props;
    let menus = [
      ...checkedKeys.artificialKeys,
      ...checkedKeys.knowledgeKeys,
      ...checkedKeys.llmKeys,
      ...checkedKeys.modelKeys,
      ...checkedKeys.robotKeys,
      ...checkedKeys.securityKeys,
      ...checkedKeys.staffKeys,
      ...checkedKeys.workOrderKeys,
    ];
    dispatch({
      type: 'authManage/addAtuhRole',
      payload: { roleName, description, menus: [...new Set(menus)].map(count => String(count)) },
      callback: res => {
        console.log(res);
        if (res.code == 0) {
          message.info(res.msg);
          this.onClose();
        };
      },
    });
  }

  editRole = () => {
    const { roleName, description, checkedKeys, authId } = this.state;
    const { dispatch } = this.props;
    let menus = [
      ...checkedKeys.artificialKeys,
      ...checkedKeys.knowledgeKeys,
      ...checkedKeys.llmKeys,
      ...checkedKeys.modelKeys,
      ...checkedKeys.robotKeys,
      ...checkedKeys.securityKeys,
      ...checkedKeys.staffKeys,
      ...checkedKeys.workOrderKeys,
    ];
    dispatch({
      type: 'authManage/editAtuhRole',
      payload: { roleName, description, menus: [...new Set(menus)].map(count => String(count)), id: authId },
      callback: res => {
        console.log(res);
        if (res.code == 0) {
          message.info(res.msg);
          this.onClose();
        };
      },
    });
  }

  renderTreeNode = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id}>{this.renderTreeNode(item.children)}</TreeNode>
        )
      };
      return <TreeNode title={item.name} key={item.id} />
    })
  }

  render() {
    const { roleName, description, menuTree, checkedKeys, expandedKeys, } = this.state;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 16 },
    };

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Card bordered={false} style={{ height: '100%' }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                  <label style={{ whiteSpace: 'nowrap' }}>{formatMessage({ id: 'authAddModal.roleName', defaultMessage: '角色名称' })}</label>
                  <Input placeholder={formatMessage({ id: 'authAddModal.inputRoleName', defaultMessage: '请输入角色名称' })} value={roleName} onChange={this.changeRoleName} maxLength={60} />
                </div>
                <div>
                  <Button onClick={this.onClose} style={{ marginRight: 8 }}>{formatMessage({ id: 'authAddModal.cancel', defaultMessage: '取消' })}</Button>
                  <Button onClick={this.onSubmit} type="primary">{formatMessage({ id: 'authAddModal.confirm', defaultMessage: '确定' })}</Button>
                </div>
              </div>
              <div>
                <div style={{ display: 'flex', gap: '12px' }}>
                  <label style={{ whiteSpace: 'nowrap' }}>{formatMessage({ id: 'authAddModal.selectModule', defaultMessage: '选择模块' })}</label>
                  {/* <Tree checkable defaultExpandAll onCheck={this.onCheck} checkedKeys={menuChecks}>{this.renderTreeNode(menuTree)}</Tree> */}
                  <div className={styles.formMenuTree}>
                    {menuTree.modelMenu && menuTree.modelMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.interactionCenter', defaultMessage: '交互中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "modelKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.modelKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.modelKeys}
                          onCheck={e => this.onCheck(e, "modelKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.modelMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    {menuTree.workOrderMenu && menuTree.workOrderMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.workOrderCenter', defaultMessage: '工单中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "workOrderKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.workOrderKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.workOrderKeys}
                          onCheck={e => this.onCheck(e, "workOrderKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.workOrderMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    {menuTree.knowledgeMenu && menuTree.knowledgeMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.knowledgeCenter', defaultMessage: '知识中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "knowledgeKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.knowledgeKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.knowledgeKeys}
                          onCheck={e => this.onCheck(e, "knowledgeKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.knowledgeMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    {menuTree.llmMenu && menuTree.llmMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.abilityCenter', defaultMessage: '能力中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "llmKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.llmKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.llmKeys}
                          onCheck={e => this.onCheck(e, "llmKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.llmMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    {menuTree.artificialMenu && menuTree.artificialMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.dataCenter', defaultMessage: '数据中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "artificialKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.artificialKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.artificialKeys}
                          onCheck={e => this.onCheck(e, "artificialKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.artificialMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    {menuTree.robotMenu && menuTree.robotMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.customerCenter', defaultMessage: '客户中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "robotKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.robotKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.robotKeys}
                          onCheck={e => this.onCheck(e, "robotKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.robotMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    {menuTree.staffMenu && menuTree.staffMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.accountCenter', defaultMessage: '账号中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "staffKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.staffKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.staffKeys}
                          onCheck={e => this.onCheck(e, "staffKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.staffMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    {menuTree.securityMenu && menuTree.securityMenu.length > 0 ? (
                      <span>
                        <span>{formatMessage({ id: 'authAddModal.securityCenter', defaultMessage: '安全中心' })}</span>
                        <Tree
                          checkable
                          onExpand={e => this.onExpand(e, "securityKeys")}
                          expandedKeys={JSON.parse(JSON.stringify(expandedKeys.securityKeys))}
                          autoExpandParent={true}
                          checkedKeys={checkedKeys.securityKeys}
                          onCheck={e => this.onCheck(e, "securityKeys")}
                          style={{ width: '300px', height: '300px', overflowX: 'hidden', overflowY: 'auto' }}
                        >
                          {this.renderTreeNode(menuTree.securityMenu)}
                        </Tree>
                      </span>
                    ) : null}
                    
                    
                  </div>
                </div>
              </div>
            </div>

          </Card>
        </PageHeaderWrapper>
      </Suspense>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AuthAddModal);

